import React from 'react';
import {App, Button, Checkbox, Form, Input, Space} from "antd";
import './Login.css';
import LoginType, {LoginResultType} from "type/LoginType";
import LogFactory from "log/LogFactory";
import {useNavigate} from "react-router-dom";
import {useAppDispatch} from "../../redux/hook";
import {loginRequest, requestGet} from "util/request";
import {LoginConstant} from "constant/LoginConstant";
import {fetchMenuTreeData} from "../../redux/reducer/navigateReducer";
import {UserPageSettingType} from "type/UserPageSetting";
import System from "global/System";
import DataStorage from "global/DataStorage";

const log = LogFactory.getLog("LoginComponent");

/**
 * 登录成功后的处理
 * @param login 登录结果
 * @param dispatch redux dispatch
 */
const loginSuccessHandler = async (login: LoginResultType,dispatch: any) => {
    log.debug("登录成功后的处理: " , login) ;
    new DataStorage<LoginResultType>().saveData("current-login-user",login) ;
    localStorage.setItem(LoginConstant.AUTHORIZATION, login.token) ;
    localStorage.setItem(LoginConstant.USERNAME, login.username) ;
    localStorage.setItem(LoginConstant.IDENTITY, login.identity) ;
    localStorage.setItem(LoginConstant.TOKEN_ID, login.tokenId) ;
    localStorage.setItem(LoginConstant.LOGIN_TIME, login.loginTime.toLocaleString()) ;
    localStorage.setItem(LoginConstant.EXPIRATION_TIME, login.expireTime.toLocaleString()) ;
    await dispatch(fetchMenuTreeData()) ;
};

/**
 * 配置页面设置数据
 */
const configPageSetting = async (username: string) => {
    const res = await requestGet<UserPageSettingType>("/manager/setting/user-page/" + username)
        .then(res => res) ;
        if (res.success){
            System.getInstance().writeConfigToLocal(res.data) ;
        }else {
            log.warn("获取用户页面设置失败: " , res) ;
        }
} ;

const LoginComponent = () => {
    const {message} = App.useApp() ;
    const [loading, setLoading] = React.useState<boolean>(false) ;
    const navigate = useNavigate() ;
    const dispatch = useAppDispatch();

    const onFinish = async (values: LoginType) => {
        setLoading(true) ;
        delete values.remember ;
        const loginRes = await loginRequest<LoginResultType>(values).then(res => res) ;
        // log.request("登录结果: " , loginRes) ;
        if (loginRes.success) {
            await loginSuccessHandler(loginRes.data,dispatch) ;
            await configPageSetting(loginRes.data.username) ;
            message.success("登录成功") ;
            navigate("/nav", {replace: true}) ;
        }else {
            message.error("登录失败") ;
            log.warn("登录失败: " , loginRes.message) ;
        }
        setLoading(false) ;
    } ;

    return (
            <div className={"video-background"}>
                <video className={"video-bg"}
                    style={{width: "100%",height: "100%",objectFit: "cover"}}
                       src={"http://192.168.2.199:8080/gvp/video/login-video.mp4"} autoPlay muted loop>
                </video>
                <div className={"login-content"}>
                    <h4 className={"login-title"}>用户登录</h4>
                    <Form <LoginType>
                         className={"login-form"}
                          name="basic"
                          labelCol={{ span: 8 }}
                          wrapperCol={{ span: 10 }}
                          initialValues={{ remember: true }}
                          onFinish={onFinish}
                          autoComplete="off"
                    >
                        <Form.Item<LoginType>
                            label="用户名"
                            name="username"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input placeholder={"请输入用户名"} />
                        </Form.Item>

                        <Form.Item<LoginType>
                            label="用户密码"
                            name="password"
                            rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                            <Input.Password placeholder={"请输入密码"} />
                        </Form.Item>

                        <Form.Item<LoginType>
                            name="remember"
                            valuePropName="checked"
                            wrapperCol={{ offset: 8, span: 16 }}
                        >
                            <Checkbox>记住我</Checkbox>
                        </Form.Item>

                        <Form.Item wrapperCol={{offset: 8,span: 16}}>
                            <Space size={100}>
                                <Button style={{boxShadow: 'none'}} loading={loading} type="primary" htmlType="submit">登录</Button>
                                <Button loading={loading} type="default" htmlType="reset">重置</Button>
                            </Space>
                        </Form.Item>
                    </Form>

                </div>
            </div>
    );
};

export default LoginComponent;